import getUserTempId from "@/utils/userTempld";
import {
    requestLogin,
    requestUserInfo,
    requestLogout
} from '@/api'


const state = {
    userTempId: getUserTempId(),
    token: localStorage.getItem("user_Token") || "",
    nickName: "",
}
const mutations = {
    SET_TOKEN_STATE(state, value) {
        state.token = value;
    },
    SET_USERNAME_STATE(state, username) {
        state.nickName = username;
    },
    SET_LOGOUT_STATE(state) {
        state.token = "";
        state.nickName = "";
        localStorage.removeItem("user_Token");
    },
}
const actions = {
    async getLogin({
        commit
    }, userInfo) {
        console.log(1);
        const result = await requestLogin(userInfo);
        console.log(result);
        commit("SET_TOKEN_STATE", result.token);
        //请求到token之后,要把token持久化到本地中,否则刷新以后vuex就没有数据了,用户需要重新登录
        localStorage.setItem("user_Token", result.token);
    },

    async getUserName({
        commit
    }) {
        try {
            console.log(2);
            const result = await requestUserInfo();
            console.log(result);
            commit("SET_USERNAME_STATE", result.nickName);
        } catch (e) {
            //在使用token发送请求的时候,如果token过期,则会抛出错误,被这里接受,我们可以清除掉token
            localStorage.removeItem("user_Token");
            //如果这里请求报错,则返回一个失败的promise实例,则dispatch方法就会返回这个失败的实例
            return Promise.reject();
        }
    },

    //退出登录
    async getLogout({
        commit
    }) {
        await requestLogout();
        commit("SET_LOGOUT_STATE");
    },
}
const getters = {}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}